﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace T4
{
    public partial class Form1 : Form
    {
        #region

        /*
         * 使用txt 后缀代替tt格式，避免修改模板文件时vs询问是否生成。 
         * 模板文件采用T4 模板 tt文件格式，使用T4 引擎生成
         * 本程序仅支持mysql，如需支持其他数据库可参考本程序实现
         * */

        public const string ModelTemplate = "Model.txt";
        public const string DALTemplate = "DapperDAL.txt";
        #endregion


        public Form1()
        {
            InitializeComponent();
            Init();
        }
        public void Init()
        {
            txtConnectionString.Text = System.Configuration.ConfigurationManager.AppSettings["constr"];
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtSchema.Text))
            {
                MessageBox.Show("数据库不能为空！");
                return;
            }

            var DBContext = new DBTools.DapperContext("db", constr);
            try
            {
                DBContext.ExecuteScalar<int>("select 1 from dual");
                MessageBox.Show("连接成功！");
            }
            catch (Exception ex)
            {
                MessageBox.Show("连接失败！" + ex.Message);
            }
        }
        /// <summary>
        /// 生成Model
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                notnull(txtSchema, "数据库不能为空!");
                notnull(txtTable, "表名不能为空!");
                notnull(txtModel, "Model类名不能为空!");
                notnull(txtNameSpace, "命名空间不能为空!");


                var DBContext = new DBTools.DapperContext("db", constr);
                txtFile.Text = txtModel.Text + ".cs";
                ModelInfo minfo = new ModelInfo()
                {
                    ConnectionString = constr,
                    DALName = txtDAL.Text.Trim(),
                    ModelName = txtModel.Text.Trim(),
                    NameSpace = txtNameSpace.Text.Trim(),
                    TableName = txtTable.Text.Trim(),
                    Schema = DBContext.OpenDB().Database
                };
                string t = T4Helper.GenerateCode(minfo, ModelTemplate);

                txtOutput.Text = t;
                MessageBox.Show("生成Model完成！");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void notnull(TextBox txt, string message)
        {
            if (string.IsNullOrWhiteSpace(txt.Text))
            {
                txt.Focus();
                throw new Exception(message);
            }
        }

        private void txtTable_TextChanged(object sender, EventArgs e)
        {
            txtModel.Text = txtTable.Text.Trim();
            txtDAL.Text = txtTable.Text.Trim() + "DAL";
        }
        /// <summary>
        /// 生成DAL文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            try
            {
                notnull(txtSchema, "数据库不能为空!");
                notnull(txtTable, "表名不能为空!");
                notnull(txtModel, "Model类名不能为空!");
                notnull(txtDAL, "DAL类名不能为空!");
                notnull(txtNameSpace, "命名空间不能为空!");

                var DBContext = new DBTools.DapperContext("db", constr);
                txtFile.Text = txtDAL.Text;

                ModelInfo minfo = new ModelInfo()
                {
                    ConnectionString = constr,
                    DALName = txtDAL.Text.Trim(),
                    ModelName = txtModel.Text.Trim(),
                    NameSpace = txtNameSpace.Text.Trim(),
                    TableName = txtTable.Text.Trim(),
                    Schema = DBContext.OpenDB().Database
                };

                string t = T4Helper.GenerateCode(minfo, DALTemplate);

                txtOutput.Text = t;
                MessageBox.Show("生成DAL完成！");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            string FilePath = String.Empty;
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            //设置文件类型  
            saveFileDialog1.Filter = " cs files(*.cs)|*.cs|txt(*.txt)|*.txt|All files(*.*)|*.*";
            //设置文件名称：
            saveFileDialog1.FileName = txtFile.Text;


            //设置默认文件类型显示顺序  
            saveFileDialog1.FilterIndex = 0;

            //保存对话框是否记忆上次打开的目录  
            saveFileDialog1.RestoreDirectory = true;

            //点了保存按钮进入  
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                //获得文件路径  
                txtFile.Text = saveFileDialog1.FileName.ToString();

                StreamWriter sw = new StreamWriter(saveFileDialog1.OpenFile());
                sw.Write(txtOutput.Text);
                sw.Flush();
                sw.Close();
                MessageBox.Show("保存完成");
            }
        }

        private void txtSchema_TextChanged(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
        public string constr
        {
            get
            {
                return txtConnectionString.Text.Trim().Replace("{dbname}", txtSchema.Text.Trim());
            }
        }
    }
}
